var sys = require('sys');
var ws  = require('websocket-server');
var sockets = [];
var server = ws.createServer();
var config = require('./config');
var route = require('./route');

exports.runServer = function(port){
	port = port || 8000;
	server.on("connection", function(connection) {
		sockets.push(connection);
		sys.puts("connect");
		connection.on("message", function(message){
			sys.puts("from client msg:"+message);
			handlerMessage(message, connection);			
	//	for (var k in sockets) {
	//		sockets[k].send("server received:"+message+"ok");
	//	}
		});
	});
	server.addListener("close", function(connection) {
		sys.puts("close");
	});
	server.listen(port);
	console.log("server start on port:"+port+"....");
};
/**
 * 所有请求的统一入口
 */
var handlerMessage = function(message, connection){
    //通过route来获取controller和action信息
    var actionInfo = route.getActionInfo(message);
    //如果route中有匹配的action，则分发给对应的action
    if(actionInfo.action){
        //假设controller都放到当前目录的controllers目录里面，还记得require是怎么搜索module的么？
        var controller = require('./controllers/'+actionInfo.controller); // ./controllers/blog
		console.log("action:"+actionInfo.action);
        if(controller[actionInfo.action]){
			var ct = new controllerContext(message, connection);
            //动态调用，动态语言就是方便啊
            //通过apply将controller的上下文对象传递给action
            controller[actionInfo.action].apply(ct,actionInfo.args);
        }else{
			console.log("controller has not action!");
        }
    }else{
		console.log("route has not action!");
        //如果route没有匹配到，则当作静态文件处理
//        staticFileServer(req, res);
    }
};
//controller的上下文对象
var controllerContext = function(message,connection){
    this.message = message;
	this.socket = connection;
};

